#from ...processor import TableProcessorObj, LeagueProcessorObj, TeamProcessorObj, MatchProcessorObj
from ...validator import validators
from ... import processor as proc
from ... import hal
from ... import halext
from ... import halext
from ..base import BaseController
from ...views import make_hal_response


class TableScoreController(BaseController):
    """俱乐部积分榜
    """    
    processor = proc.TableProcessorObj
    document = halext.TableWithCupSchema
    collection = halext.TableWithRankCollection

    def c(self, collection):
        return {'tables': collection}

    def d(self, document):
        return {'tables': document}

    def cuprank(self, leagueID):
        r = proc.TeamProcessorObj.group(leagueID) 
        l = []

        for  v in r:
            print('$'*80)
            print(v)            
            print('$'*80)
            g = v 
            q = proc.TableProcessorObj.rank_by_group(v)
            l.append({"groupName":g, "data":q})

        print('*'*80)
        print(repr(l))
        print('*'*80)

        q = proc.MatchProcessorObj.query_type_by_leagueid(leagueID) 
        ll = []
        for v in q:
            q = proc.MatchProcessorObj.read(leagueid=leagueID, type = v.type)
            ll.append({'name':v.type, 'data':q})
        
        print('*'*80)
        print(repr(ll))
        print({'Elimination':ll,'scoreboard':l})
        print('*'*80)
        return {'Elimination':ll,'Scoreboard':l}


    def get(self, *args, **kwargs):
        #leagueid = get_parameter(kwargs, ('leagueID', 'leagueid'))
        leagueid = kwargs.get('leagueID')
        #r = self.dbh.query(db.League).filter(db.League.leagueid == leagueid).first()
        r = proc.LeagueProcessorObj.read(leagueid = leagueid)
        print('*'*80)
        print(repr(r))
        print('*'*80)

        if r:
           if  r[0].type == 0:
               data =  processor.rank(leagueid)
           elif  r[0].type == 1:
               data =  self.cuprank(leagueid)
           else:
               return None

        serialized = self.serialize(data)
        print('!'*80)
        print(serialized)
        print('!'*80)
        return make_hal_response(serialized)

